package com.my.study.service.impl;

import com.my.study.dao.MyUserDao;
import com.my.study.dto.JwtUserDto;
import com.my.study.entity.MyUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Carlos
 * @version 1.0.0
 * @date 2022/1/7 8:42
 */
@Slf4j
@Service("userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {
    
    private static final Map<String, String> USER_MAP = new HashMap<>();
    static PasswordEncoder PE = new BCryptPasswordEncoder(10);
    static {
        USER_MAP.put("ths_admin", PE.encode("123456"));
        USER_MAP.put("ths_admin1", PE.encode("123456"));
        USER_MAP.put("ths_admin2", PE.encode("123456"));
        USER_MAP.put("ths_admin3", PE.encode("123456"));
    }
    

    @Autowired
    private MyUserDao myUserDao;

    @Override
    public JwtUserDto loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("Loading userName : {}", userName);
        String password = USER_MAP.get(userName);
        if (null == password) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        
        MyUserEntity myUser = new MyUserEntity();
        myUser.setUserName(userName);
        myUser.setPassword(password);
//        MyUserEntity myUser = myUserDao.findByName(userName);
//        if (null == myUser) {
//            throw new UsernameNotFoundException("用户名不存在!");
//        }
        log.info("myUser = {}", myUser);
        JwtUserDto jwtUserDto = new JwtUserDto(myUser);
        // 创建角色[ROLE_admin]、和权限[sys:find]
        jwtUserDto.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_admin", "sys:find"));
        return jwtUserDto;
    }
}
